package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.DbanAuthRecord;
import org.jeecg.modules.system.entity.DbanInformation;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.DbanAuthRecordMapper;
import org.jeecg.modules.system.mapper.DbanInformationMapper;
import org.jeecg.modules.system.service.IDbanAuditInfoService;
import org.jeecg.modules.system.service.IDbanInformationService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.MybatisParameterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IDbanAuditInfoServiceImpl extends ServiceImpl<DbanAuthRecordMapper, DbanAuthRecord> implements IDbanAuditInfoService {

    @Resource
    private DbanAuthRecordMapper dbanAuthRecordMapper;
    @Autowired
    private SysBaseApiImpl sysBaseApi;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IDbanInformationService iDbanInformationService;
    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private DbanInformationMapper dbanInformationMapper;

    @Override
    public List<DbanAuthRecord> queryInfo(DbanAuthRecord dbanAuthRecord) {
        List<DbanAuthRecord> authRecords = dbanAuthRecordMapper.query(dbanAuthRecord);
        return authRecords;
    }

    @Override
    public int deleteByPkId(Integer pkId) {
        return dbanAuthRecordMapper.deleteByPkId(pkId);
    }

    @Override
    public List<DbanAuthRecord> queryByPkIds(List<Integer> pkIds) {
        return dbanAuthRecordMapper.queryByPkIds(pkIds);
    }

    @Override
    public List<DbanAuthRecord> queryByUserIds(List<String> userIds) {
        return dbanAuthRecordMapper.queryByUserIds(userIds);
    }

    //=============================================================================================================
    @Override
    public IPage<DbanInformation> pageListAuditInfo(DbanInformation dbanInformation,
                                                    Integer pageNo,
                                                    Integer pageSize,
                                                    HttpServletRequest req) {

        Integer status = dbanInformation.getStatus();
        dbanInformation.setStatus(null);  //把参数status初始化
        //地市审核员查询条件
        String latestAuditUserId = dbanInformation.getLatestAuditUserId();
        dbanInformation.setLatestAuditUserId(null);

        /**
         * 首先获取登录人的是省级的还是地市级的
         * 1、地市级的审核员只能看自己的审核记录
         * 2、省级审核员能看所有的审核记录
         */
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        String userId = sysUser.getId();
        List<String> roles = sysBaseApi.getRolesByUsername(username);

        QueryWrapper<DbanInformation> queryWrapper = null;

        if (roles.contains("province_asset_audit") || roles.contains("province_asset_edit")) {
            //省级审核员能看所有的审核记录
            queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());

            if (status == 0) {
                //省级待审核
                queryWrapper.eq("status", 1);
            } else {
                //查看所有省级审核人员审核的记录信息（查询所有省级人员审核的Pkid）
                List<SysUser> shengJiAuditUserInfo = iSysUserService.getShengJiAuditUserInfo();
                List<String> userIds = new ArrayList<>();
                for (SysUser index : shengJiAuditUserInfo) {
                    userIds.add(index.getId());
                }
                List<DbanAuthRecord> dbanAuthRecords = this.queryByUserIds(userIds);
                if (!CollectionUtils.isEmpty(dbanAuthRecords)) {
                    Set<Integer> pkIdSet = new HashSet<>();
                    for (DbanAuthRecord index : dbanAuthRecords) {
                        pkIdSet.add(index.getPkId());
                    }
                    List<Integer> pkIdList = new ArrayList<>(pkIdSet);
                    MybatisParameterUtils.cutInParameter(queryWrapper, "id", pkIdList);
                    //根据传递的参数重新组织针对审核状态的status的查询条件
                    if (status == 1) {
                        //省级已审核
                        queryWrapper.eq("status", 3);
                    } else if (status == 2) {
                        //省级已退回 所有省级审核员操作的
                        queryWrapper.and(qr -> qr.eq("status", 2).or().eq("status", 4));
                    } else if (status == 900) {
                        //备选入库
                        queryWrapper.eq("status", 900);
                    } else {
                        throw new RuntimeException("==>没有此参数:{}" + status);
                    }
                } else {
                    //没有审核数据,给一个不存在的数据条件
                    queryWrapper.in("id", 0);
                }
            }
        } else {
            /**
             *地市级的审核员只能看自己的审核记录
             * 根据登录人的user_id查询审核记录表中的数据
             */
            queryWrapper = QueryGenerator.initQueryWrapper(dbanInformation, req.getParameterMap());
//            List<String> userIds = new ArrayList<>();
//            userIds.add(userId);
//            List<DbanAuthRecord> dbanAuthRecords = this.queryByUserIds(userIds);
//            if(!CollectionUtils.isEmpty(dbanAuthRecords)) {
//                Set<Integer> pkIdSet = new HashSet<>();
//                for (DbanAuthRecord index : dbanAuthRecords) {
//                    pkIdSet.add(index.getPkId());
//                }
//                List<Integer> pkIdList = new ArrayList<>(pkIdSet);
//                MybatisParameterUtils.cutInParameter(queryWrapper,"id", pkIdList);
            List<String> departIdList = sysBaseApi.getDepartIdsByUsername(username);
            String departIds = String.join(",", departIdList);
            if (!CollectionUtils.isEmpty(departIdList)) {
                if (departIdList.size() == 1) {
                    queryWrapper.like("dept_ids", departIdList.get(0));
                } else {
                    for (int i = 0; i < departIdList.size(); i++) {
                        if (i == 0) {
                            queryWrapper.apply(null != departIdList.get(i), "(find_in_set({0},dept_ids)", departIdList.get(i));
                        } else {
                            if (i == departIdList.size() - 1) {
                                queryWrapper.or().apply(null != departIdList.get(i), "find_in_set({0},dept_ids))", departIdList.get(i));
                            } else {
                                queryWrapper.or().apply(null != departIdList.get(i), "find_in_set({0},dept_ids)", departIdList.get(i));
                            }
                        }
                    }
                }
            }
            //根据传递的参数重新组织针对审核状态的status的查询条件
            if (status == 0) {
                //市级待审核
                queryWrapper.and(qr -> qr.eq("status", 0).or().eq("status", 2));
            } else if (status == 1) {
                //市级已审核
                queryWrapper.and(qr -> qr.eq("status", 1).or().eq("status", 3).or().eq("status", 900));
            } else if (status == 2) {
                //市级已退回
                queryWrapper.eq("status", 4);
            } else {
                throw new RuntimeException("==>没有次参数:{}" + status);
            }
//            }else{
//                //没有审核数据,给一个不存在的数据条件
//                queryWrapper.in("id", 0);
//            }

        }
        //区分五个一批好成果和基础资源的审核列表
        String type = dbanInformation.getType();
        if (StringUtils.isBlank(type) || !type.equals("五个一批好成果")) {
            queryWrapper.ne("type", "五个一批好成果");
        }
        //地市审核员查询条件
        if (StringUtils.isNotBlank(latestAuditUserId)) {
            List<String> latestUser = new ArrayList<>();
            latestUser.add(latestAuditUserId);
            List<DbanAuthRecord> dbanAuthRecordsParam = this.queryByUserIds(latestUser);
            if (!CollectionUtils.isEmpty(dbanAuthRecordsParam)) {
                Set<Integer> pkIdSet = new HashSet<>();
                for (DbanAuthRecord index : dbanAuthRecordsParam) {
                    pkIdSet.add(index.getPkId());
                }
                List<Integer> pkIdList = new ArrayList<>(pkIdSet);
                MybatisParameterUtils.cutInParameter(queryWrapper, "id", pkIdList);
            } else {
                //查询条件不存在，构建一个不存在的条件
                queryWrapper.in("id", 0);
            }
        }
        //构建查询条件完成之后进行查询操作
        Page<DbanInformation> page = new Page<DbanInformation>(pageNo, pageSize);

        IPage<DbanInformation> pageList = iDbanInformationService.page(page, queryWrapper);

        //==============================================================================================================
        //挂接地市、市审核员、流转状态、审核时间
        List<DbanInformation> records = pageList.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            //获取地市级审核员信息
            List<SysUser> diJiAuditUserInfo = iSysUserService.getDiJiAuditUserInfo();
            Map<String, String> dijiMap = new HashMap<>();
            for (SysUser index : diJiAuditUserInfo) {
                dijiMap.put(index.getUsername(), index.getRealname());
            }
            //获取所有用户，定位是审核员使用
            List<Integer> idList = records.stream().map(DbanInformation::getId).collect(Collectors.toList());
            List<DbanAuthRecord> dbanAuthRecords = this.queryByPkIds(idList);
            Map<Integer, String> mapPkId = new HashMap<>();
            for (DbanAuthRecord index : dbanAuthRecords) {
                if (dijiMap.containsKey(index.getUserName())) {
                    mapPkId.put(index.getPkId(), index.getRealName());
                }
            }

            //按照时间排序，取list集合中的第一个 PKID-key
            Map<Integer, List<DbanAuthRecord>> map = dbanAuthRecords.stream().collect(Collectors.groupingBy(DbanAuthRecord::getPkId));
            SimpleDateFormat sb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (DbanInformation index : records) {
                String deptIds = index.getDeptIds();//暂时考虑一个用户属于一个地市的情况
                SysDepart sysDepartEntity = sysDepartService.getById(deptIds);
                String departName = sysDepartEntity.getDepartName();
                index.setCityName(departName);
                Integer id = index.getId();
                List<DbanAuthRecord> authRecordList = map.get(id);
                DbanAuthRecord record = authRecordList.get(0);//按照时间排序，取list集合中的第一个
                index.setAuditStatus(record.getStatusTxt());
                index.setAuditDate(sb.format(record.getCreateTime()));
                //对应的市审核员
                String cityAuditUserName = mapPkId.get(id);
                index.setCityAuditUserName(cityAuditUserName);

            }
        }
        //==============================================================================================================
        return pageList;
    }
}
